<?php

namespace App\Http\Controllers\Backend\User;

use Illuminate\Http\Request;
use App\Common\Utils\Common;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
use App\Http\Models\User\LoginFrom;
use App\Http\Models\Log\LogService;
use App\Http\Controllers\Backend\BackendController;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends BackendController
{
    /*
      |--------------------------------------------------------------------------
      | Login Controller
      |--------------------------------------------------------------------------
      |
      | This controller handles authenticating users for the application and
      | redirecting them to your home screen. The controller uses a trait
      | to conveniently provide its functionality to your applications.
      |
     */

use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware('guest')->except('logout');
    }

    //重写登录跳转页面
    public function showLoginForm() {
        return view("backend.login.login");
    }

    //后台登录
    public function signIn(LoginFrom $request) {
        try {
            $rememberPassword = false;
            if ($request->rememberPassword) {
                $rememberPassword = true;
            }
            if (Auth::attempt(['username' => $request->username, 'password' => $request->password], $rememberPassword)) {
                $admin = [
                    'username' => Auth::user()->id,
                    'info' => md5(Common::getSessionToken($request->getSession()) . Auth::user()->id),
                ];
                if (Auth::user()->status == 0) {
                    Auth::logout();
                    $request->session()->flush();
                    return back()->with('errorMsg', '账号已被禁用');
                }
                //            //单点登录
//                Cache::put('loginToken', $admin, 60 * 5);
//                $logModel = new LogService;
//                $logModel->create("用户登陆-" . Auth::user()->username);
                return redirect()->intended("admin/index");
            } else {
                return back()->with('errorMsg', '账号或密码错误');
            }
        } catch (\Exception $ex) {
            return back()->with('errorMsg', $ex->getMessage());
        }
    }

    //退出
    public function logout(Request $request) {
        Auth::logout();
        $request->session()->flush();
        Cache::forget('loginToken');
        return redirect()->intended('admin/login');
    }

}
